package com.uinnova.product.eam.workable.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.uinnova.product.eam.workable.util.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.engine.HistoryService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.history.HistoricProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Component("childPublicAccessUserInfoListener")
public class ChildPublicAccessUserInfoListener implements ExecutionListener {

    @Resource
    private RestTemplate restTemplate;

    @Value("${generic.user.url}")
    private String genericUserUrl;

    @Resource
    private HttpUtil httpUtil;

    @Autowired
    private transient HistoryService historyService;

    @Override
    public void notify(DelegateExecution execution) {
        //获取当前任务的id
        FlowElement currentFlowElement = execution.getCurrentFlowElement();
        String taskDefinitionId = currentFlowElement.getDocumentation();
        log.info("当前任务定义id：{}", taskDefinitionId);

        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(execution.getProcessInstanceId())
                .singleResult();
        //获取流程定义id
        String splitProcessDefinitionId = historicProcessInstance.getProcessDefinitionKey();
        log.info("当前流程定义id：{}", splitProcessDefinitionId);
        //获取当前子流程实例的数据，目前子流程使用的嵌入子流程，故获取的是主流程的业务主键，这里
        //将存入约定好的变量直接返回,业务方
        Object childVariable = execution.getVariable("childVariable");
        if(childVariable!=null){
            JSONObject jsonObject = JSON.parseObject(childVariable.toString());
            String childProcessInstanceBusinessKey = jsonObject.getString("childBusinessKey");
            String diagramType = jsonObject.getString("diagramType");

            log.info("当前子流程业务主键：{}", childProcessInstanceBusinessKey);
            //TODO 远程调用eam获取不同节点不同人员审批的人员信息 genericUserUrl需要加入到白名单
            String requestUrl = genericUserUrl + "?defKey=" + splitProcessDefinitionId + "&businessKey=" + childProcessInstanceBusinessKey + "&taskKey=" + diagramType;
            log.info("获取通用审批用户请求的url:{}", requestUrl);
            List<String> userLoginCodes = httpUtil.get(requestUrl, List.class);
            log.info("获取审批用户列表:{}", userLoginCodes);
            Map<String, Object> variables = execution.getVariables();
            if (!CollectionUtils.isEmpty(userLoginCodes)) {
                log.info("审批用户：{}", userLoginCodes);
                String currentActivityId = execution.getCurrentActivityId();
                log.info("执行器id{}", currentActivityId);
                variables.put("assigneeList", userLoginCodes);
            }
            execution.setVariables(variables);
        }
    }
}
